# Licensed to the Apache Software Foundation (ASF) under one
# or more contributor license agreements.  See the NOTICE file
# distributed with this work for additional information
# regarding copyright ownership.  The ASF licenses this file
# to you under the Apache License, Version 2.0 (the
# "License"); you may not use this file except in compliance
# with the License.  You may obtain a copy of the License at
#
#   http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing,
# software distributed under the License is distributed on an
# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
# KIND, either express or implied.  See the License for the
# specific language governing permissions and limitations
# under the License.
"""Serve logs process."""

from __future__ import annotations

import socket
import sys

import structlog
import uvicorn

from airflow.configuration import conf

logger = structlog.get_logger(__name__)


def serve_logs(port=None):
    """Serve logs generated by Worker."""
    # setproctitle causes issue on Mac OS: https://github.com/benoitc/gunicorn/issues/3021
    os_type = sys.platform
    if os_type == "darwin":
        logger.debug("Mac OS detected, skipping setproctitle")
    else:
        from setproctitle import setproctitle

        setproctitle("airflow serve-logs")

    port = port or conf.getint("logging", "WORKER_LOG_SERVER_PORT")

    if socket.has_dualstack_ipv6():
        serve_log_uri = f"http://[::]:{port}"
    else:
        serve_log_uri = f"http://0.0.0.0:{port}"

    logger.info("Starting log server on %s", serve_log_uri)

    # Use uvicorn directly for ASGI applications
    uvicorn.run("airflow.utils.serve_logs.log_server:get_app", host="", port=port, log_level="info")
    # Log serving is I/O bound and has low concurrency, so single process is sufficient


if __name__ == "__main__":
    serve_logs()
